﻿//var _iLastPickedIndex = -1;
var _oPreviewed, _oXml, _oPop, _o, _iPopH, _iPopW, _oXslProc;

var KEY_SELECTALL;
var KEY_ENTER = 13;
var KEY_SPACE = 32;
var KEY_UP = 38;
var KEY_DOWN = 40;
var KEY_LEFT = 37;
var KEY_RIGHT = 39;

var GRID_SUPPORT_PREVIEW = false;
var GRID_SUPPORT_MULTISELECT = true;

/*
function window.onload()
{
initGrid();
	
// Localizable Select All Key
KEY_SELECTALL = "A".charCodeAt(0);
}
*/

function initGrid(oTable) {
    var iTotalRecords = 0;

    // Get the total number or records if there are any
    //if (typeof(oTable) != "undefined" && oTable.rows[0].oid)
    if (typeof (oTable) != "undefined") {
        iTotalRecords = oTable.rows.length - 1;
    }

    oTable._iNumSelected = 0;
    oTable._iLastPickedIndex = -1;
    oTable._iTotalRecords = iTotalRecords;

    // If there are records in the grid, select the first record
    if (iTotalRecords > 0) {
        var strLocation = "";
        if (document.all(oTable.gridID + ":txtLocation"))
            strLocation = document.all(oTable.gridID + ":txtLocation").value;
        var arrLocation = strLocation.split(",");
        var bFlag;
        for (var i = 1; i < oTable.rows.length; i++) {
            bFlag = false;
            for (var j = 0; j < arrLocation.length; j++) {
                if (oTable.rows[i].oid == arrLocation[j]) {
                    selectRow(oTable, oTable.rows[i]);
                    bFlag = true;
                    break;
                }
            }
            if (!bFlag) {
                unselectRow(oTable, oTable.rows[i]);
                applyStyle(oTable.rows[i], "gridSelectOff");
                //applyStyleTR(oTable.rows[i], (i%2==0)?"gridAltRow":"gridRow");
            }
        }

        if (oTable._iNumSelected == 0) selectRow(oTable, oTable.rows[1]);
        if (document.all(oTable.gridID + ":txtLocation"))
            document.all(oTable.gridID + ":txtLocation").value = getSelected(oTable.id);
    }
}

function getSelected(sGridName) {
    var iTotal = document.all(sGridName)._iNumSelected;
    if (iTotal == 0) return false;
    var o = document.all(sGridName);
    var a = new Array(iTotal);
    var ii = 0;
    for (var i = 1; i < o.rows.length; i++) {
        if (o.rows[i].selected) {
            a[ii] = o.rows[i].oid;
            ii++;
        }
        if (ii == iTotal) break;
    }
    return a;
}

function getSelectedTr(sGridName)//^^新增函数
{
    var iTotal = document.all(sGridName)._iNumSelected;
    if (iTotal == 0) return false;
    var o = document.all(sGridName);
    var aTr = new Array(iTotal);
    var ii = 0;
    for (var i = 1; i < o.rows.length; i++) {
        if (o.rows[i].selected) {
            aTr[ii] = o.rows[i];
            ii++;
        }
        if (ii == iTotal) break;
    }
    return aTr;
}

// Brings up the preview print window containing all details of the object (row item) passed in
function printRowDetails(o) {
    openStdWin("/_forms/print/print.aspx?objectType=&id=" + o.oid, "print" + buildWinName(o.oid));
}

// Automagically sets the title of the NOBR to it's inner text to allow for auto-ellipse text viewing
function RenderToolTip() {
    var o = event.srcElement;

    if (o && o.tagName == "NOBR" && o.title == "" && o.innerText != "") {
        o.title = o.innerText;
    }
}






/*
START USER INPUT CODE
=====================
*/
function handleDblClick(oTable) {
    var oTr = event.srcElement;

    while ((oTr.tagName != "TR") || (!oTr.oid)) {
        oTr = oTr.parentElement;
        if (oTr == null) return; 	// ignore the dragged cursor command
    }

    if (typeof (doTrDblClick) == "function") {
        doTrDblClick(oTr);
    }
}

function handleClick(o) {
    if (!o) {
        o = event.srcElement;
    }

    while ((o.tagName != "TR") || (!o.oid)) {
        o = o.parentElement;
        if (o == null) return; 	// ignore the dragged cursor command
    }

    /*
    // The structure of the grid HTML is known, the falls below are intentional to find the
    // TR object corrisponding to the user's request
    switch (o.tagName)
    {
    case "INPUT":
    case "TBODY":
    // Special case for user dragging on the grid
    return false;

		case "IMG":	
    // fall

		case "NOBR":
    o = o.parentElement;
    // fall

		case "TD":
    o = o.parentElement;
    break;
    }
    */

    if (o.rowIndex == 0) return; 		//第一行标题跳过

    var oTable = o.parentElement.parentElement;

    //取消全选复选框
    if (oTable.rows[0]) {
        if (oTable.rows[0].cells[0]) {
            if (oTable.rows[0].cells[0].children[0]) {
                oTable.rows[0].cells[0].children[0].checked = false;
            }
        }
    }

    if (!o.selected) {
        handleSelectRow(oTable, o);
    }
    else if (event && event.ctrlKey && oTable._iNumSelected > 1) {
        unselectRow(oTable, o);
    }
    else {
        oTable._iLastPickedIndex = o.rowIndex;
        unselectRows(oTable, o);
    }
    if (document.all(oTable.gridID + ":txtLocation"))
        document.all(oTable.gridID + ":txtLocation").value = getSelected(oTable.id);
}

function document.onkeyup1() {
    var oTable = gridBar;

    // We don't currently handle multi-select with keyboard only & make sure this is a full grid
    if (event.altKey || event.shiftKey || (event.ctrlKey && event.keyCode != KEY_SELECTALL) ||
		typeof (oTable) == "undefined") {
        return false;
    }

    // Handle various keyboard commands
    switch (event.keyCode) {
        case KEY_SELECTALL:
            if (event.ctrlKey && GRID_SUPPORT_MULTISELECT && window.parent._iTotalRecords > 0) {
                selectAllRows();
            }
            break;

        case KEY_ENTER:

            if (window.parent._iTotalRecords > 0) {
                oTable.rows[oTable._iLastPickedIndex].fireEvent("ondblclick");
            }
            break;

        case KEY_DOWN:
            if (oTable._iLastPickedIndex < oTable.rows.length - 1) {
                unselectRows();

                var i = oTable._iLastPickedIndex + 1;

                // Skip over the Preview TR
                if (oTable.rows[i].cells[0].className == "gridPreview") {
                    i++;
                }

                oTable.rows[i].fireEvent("onclick");
            }
            break;

        case KEY_UP:
            if (oTable._iLastPickedIndex > 0) {
                unselectRows();

                var i = oTable._iLastPickedIndex - 1;

                // Skip over the Preview TR
                if (oTable.rows[i].cells[0].className == "gridPreview") {
                    i--;
                }

                oTable.rows[i].fireEvent("onclick");
            }
            break;

        case KEY_SPACE:
            expandRow(oTable.rows[oTable._iLastPickedIndex]);
            break;

        case KEY_RIGHT:
            window.parent._oGridStatusBar.LoadPage(true);
            break;

        case KEY_LEFT:
            window.parent._oGridStatusBar.LoadPage();
            break;
    }
}

/*
END USER INPUT CODE
===================
*/









/*
START ROW SELECTION HELPER CODE
===============================
*/

//全选记录行
//所在的 Table 上设置 MultiSelect，true 为允许多选，false 为不允许多选。
function doCheckAll(o) {
    var oTable;

    oTable = o.parentElement;
    while ((oTable.tagName != "TABLE")) {
        oTable = oTable.parentElement;
        if (oTable == null) return;
    }

    //是否允许多选
    if (oTable.MultiSelect != "true") return;

    if (o.checked) {
        selectAllRows(oTable);
    }
    else {
        unselectRows(oTable);
        if (oTable._iTotalRecords > 0) {
            handleSelectRow(oTable, oTable.rows[1]);
        }
    }
}

function handleSelectRow(oTable, o) {
    //if (event && event.shiftKey && GRID_SUPPORT_MULTISELECT && oTable._iLastPickedIndex != -1)
    if (event && event.shiftKey && oTable.MultiSelect == "true" && oTable._iLastPickedIndex != -1) {
        unselectRows(oTable, o);

        if (o.rowIndex < oTable._iLastPickedIndex) {
            selectRows(oTable, o.rowIndex, oTable._iLastPickedIndex);
        }
        else {
            selectRows(oTable, oTable._iLastPickedIndex, o.rowIndex);
        }
    }
    else {
        selectRow(oTable, o);

        //if (event && !event.ctrlKey || !GRID_SUPPORT_MULTISELECT)
        if (event && !event.ctrlKey || oTable.MultiSelect != "true") {
            unselectRows(oTable, o);
        }

        oTable._iLastPickedIndex = o.rowIndex;
    }
}

function selectRow(oTable, o) {
    if (!o.selected && o.firstChild.className != "gridPreview") {
        oTable._iNumSelected++;
        o.selected = true;
        o.style.paddingTop = "0px";
        applyStyle(o, "gridSelectOn");
        //applyStyleTR(o, "gridSelectOn");
    }
}

function unselectRow(oTable, o) {
    if (o.selected) {
        oTable._iNumSelected--;
        o.selected = false;
        o.style.paddingTop = "1px";
        applyStyle(o, "gridSelectOff");
        //applyStyleTR(o, (o.rowIndex%2==0)?"gridAltRow":"gridRow");
    }
}

function selectAllRows(oTable) {
    selectRows(oTable, 1, oTable.rows.length - 1);
}

// Selects a range of rows
function selectRows(oTable, iStart, iStop) {
    for (iStart; iStart < iStop + 1; iStart++) {
        selectRow(oTable, oTable.rows[iStart]);
    }
}

// Unselects ALL rows skipping the one provided
function unselectRows(oTable, oSkip) {
    for (var i = 1; i < oTable.rows.length; i++) {
        var oTr = oTable.rows[i];

        if (oTr !== oSkip) {
            unselectRow(oTable, oTr);
            //collapseRow(oTable, oTr);
        }
    }
}

function applyStyle(o, sClass) {
    /*
    var i = 0;
    var ii = o.cells.length;

	while (i < ii)
    {
    o.cells[i].className = sClass;
    i++;
    }
    */
    o.className = sClass;
}

function applyStyleTR(o, sClass) {
    o.className = sClass;
}

/*
END ROW SELECTION HELPER CODE
=============================
*/










/*
START CONTEXT MENU RELATED SCRIPT
*/

function document.oncontextmenu() {
    return false; 			// 屏蔽右键菜单

    _o = event.srcElement;
    event.returnValue = false;

    while (_o.tagName != "TR" && _o.tagName != "BODY") {
        _o = _o.parentElement;
    }

    // Disable Popup Items
    popupToggle(!_o.oid);

    // Create and cache the popup object
    if (!_oPop) {
        _oPop = window.createPopup();

        var oS = _oPop.document.createStyleSheet();
        oS.addRule("HR", "margin-bottom:1px;");
        oS.addRule("div.item", "cursor:hand;padding:3px;padding-left:15px;");

        // Temp Render the Popup for sizing	
        _oPop.show(0, 0, 0, 0);

        with (_oPop.document.body) {
            innerHTML = divMenu.outerHTML;

            with (firstChild) {
                style.display = "";
                onmouseover = popGlow;
                onmouseout = popGlow;
                _iPopH = offsetHeight;
                _iPopW = offsetWidth + 10; // 10px = Padding
            }
        }

        // Cache the current window object for inline script to call
        _oPop.document.oParent = window;
    }

    _oPop.show(event.screenX - 1, event.screenY - 5, _iPopW, _iPopH);
}

function popGlow() {
    o = _oPop.document.parentWindow.event.srcElement;

    if (o.tagName == "NOBR") {
        o = o.parentElement;
    }

    if (o.id == "divMenu" || o.tagName == "HR") {
        return;
    }

    with (o.runtimeStyle) {
        if (color == "highlighttext") {
            color = backgroundColor = "";
        }
        else {
            color = "highlighttext";
            backgroundColor = "highlight";
        }
    }
}

function popupToggle(b) {
    // The NOBR Tag causes a bug in .children so we have to use .ALL
    var o = divMenu.all.tags("div");

    // "Magic" code to determine what should be disabled and not
    if (o.length > 1 && o[0].disabled != b) {
        o[0].disabled = o[1].disabled = b;
        _oPop = null;
    }
}

/*
END CONTEXT MENU RELATED SCRIPT
*/







/*
START PREVIEW CODE
==================
*/
function collapseRow(oTable, oTr) {
    if (oTr.expanded) {
        oTr.cells[0].firstChild.src = "imgs/r.gif";
        oTable.deleteRow(oTr.rowIndex + 1);
        oTr.expanded = false;
        _oPreviewed = null;
    }
}

function expandRow(oTable, oTr) {
    if (!GRID_SUPPORT_PREVIEW) {
        return false;
    }

    // If this Row is previewed or there is another expanded row, collapse them
    if (oTr.expanded) {
        collapseRow(oTable, oTr);
        return;
    }
    else if (_oPreviewed) {
        collapseRow(oTable, _oPreviewed);
    }

    // If this is multi-object grid, reset the XSL Transform to force a reload
    if (oTr.otype != undefined) {
        var sType = oTr.otype;
        _oXslProc = null;
    }
    else {
        var sType = oTable.oname;
    }

    // Create and cache an XML Document for Preview Data
    if (!_oXml) {
        _oXml = new ActiveXObject("Microsoft.XMLDOM");
        _oXml.async = false;
    }

    _oXml.load("/_grid/preview.aspx?type=" + sType + "&id=" + oTr.oid);

    // This will preserve user entered tags exactly as they were entered,
    // emails have CDATA protection
    if (parseInt(sType, 10) != EmailActivity) {
        var sXml = _oXml.xml;
        sXml = sXml.replace(/&/gi, "&amp;");
        _oXml.loadXML(sXml);
    }

    if (!handleXMLErr(_oXml)) {
        return;
    }

    // If it doesn't exist, create and cache an XSL Transform
    if (!_oXslProc) {
        var oXslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
        oXslDoc.async = false;
        oXslDoc.resolveExternals = false;
        oXslDoc.load("/_xslfiles/" + sType + "_preview.xsl");

        var oXslt = new ActiveXObject("Msxml2.XSLTemplate");
        oXslt.stylesheet = oXslDoc;

        _oXslProc = oXslt.createProcessor();
        _oXslProc.addParameter("languageCode", ORG_LANGUAGE_CODE);
        _oXslProc.addParameter("numberFormat", ORG_NUMBER_FORMAT);
        _oXslProc.addParameter("numberFormatMask", ORG_NUMBER_FORMAT_MASK);
        _oXslProc.addParameter("timeFormat", ORG_TIME_FORMAT);
        _oXslProc.addParameter("currencySymbol", ORG_CURRENCY_SYMBOL);
        _oXslProc.addParameter("dateSeparator", ORG_DATE_SEPARATOR);
        _oXslProc.addParameter("dateFormat", ORG_DATE_FORMAT);
    }

    _oXslProc.input = _oXml;
    _oXslProc.transform();


    // Setup Preview Row
    var oNewTR = oTable.insertRow(oTr.rowIndex + 1);

    oNewTR.oid = oTr.oid; 	// Assign id and otype to the new row (preview)
    if (oTr.otype) {
        oNewTR.otype = oTr.otype;
    }

    with (oNewTR) {
        style.height = "100%";
        onmouseover = function y() { window.event.cancelBubble = true };
        onclick = function x() { window.event.cancelBubble = true };
    }

    // Setup Preview Cell
    var oTD = oNewTR.insertCell(0);

    with (oTD) {
        className = "gridPreview";
        colSpan = oTr.cells.length;
        innerHTML = (EmailActivity == sType) ? decodeXml(_oXslProc.output) : _oXslProc.output;
        scrollIntoView(false);
    }

    oTr.expanded = true;
    oTr.style.paddingTop = "0px";
    oTr.cells[0].firstChild.src = "imgs/d.gif";

    _oPreviewed = oTr;
}

/*
END PREVIEW CODE
================
*/

//删除行记录(公用函数)	add by taoh 2006-01-26
function delRow(sGridBar) {
    if (sGridBar == undefined) sGridBar = "gridBar";
    var o = document.all(sGridBar);

    var iTotal = o._iNumSelected;
    if (iTotal == 0) return false;

    if (confirm("确实要删除选择的记录吗？") == false) { return; }

    //var o = document.all("gridBar");

    var strdel = "";

    for (var i = 1; i < o.rows.length; i++) {
        if (o.rows[i].selected) {
            strdel = strdel + "," + i;
        }
    }

    if (strdel != "") {
        strdel = strdel.substring(1);
        var ps = strdel.split(",");

        // 校验开始

        // 校验结束

        for (var row = ps.length - 1; row >= 0; row--) {
            o.rows[ps[row]].removeNode(true);
        }

        //删除完成后
        if (o.rows.length > 1) {
            // 需要对行的序号重整
            for (var i = 1; i < o.rows.length; i++) {
                o.rows[i].children[0].innerHTML = i;
            }
            // 默认选中第一行
            //unselectRows(gridBar, null);
            //selectRow(gridBar,o.rows[1])
            o.rows[1].click();

            // 未全部删除要把所选行数置1
            o._iNumSelected = 1;
        }
        else {
            // 全部删除完要把所选行数清零
            o._iNumSelected = 0;
        }
    }
}